package com.woniuxy.userassembly.apiimpl;



import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.aliyun.oss.OSS;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;

import com.woniuxy.api.UserApi;
import com.woniuxy.common.Result;
import com.woniuxy.form.UpdUserForm;
import com.woniuxy.form.UserFinanceForm;
import com.woniuxy.form.UserForm;
import com.woniuxy.form.UserVo;
import com.woniuxy.userassembly.config.JWTHelper;
import com.woniuxy.userassembly.model.AppConstants;
import com.woniuxy.userassembly.model.PayOrder;
import com.woniuxy.userassembly.model.User;
import com.woniuxy.userassembly.model.UserFinance;
import com.woniuxy.userassembly.service.AliPayService;
import com.woniuxy.userassembly.service.IUserFinanceService;
import com.woniuxy.userassembly.service.IUserGradeService;
import com.woniuxy.userassembly.service.IUserService;
import com.woniuxy.userassembly.utils.AliyunSmsUtils;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Liyfi
 * @since 2021-05-22
 */
@RestController
@Slf4j
public class UserController implements UserApi {
    @Autowired
    private IUserService service;

    @Autowired
    private IUserGradeService gradeService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OSS oss;

    @Autowired
    private AliPayService aliPayService;

    @Autowired
    private IUserFinanceService iUserFinanceService;

    @Autowired
    private JWTHelper jwtHelper;


//    private  final String CODE=AliyunSmsUtils.getNewcode();


    /**
     * 注册
     * @param form
     * @return
     */
    @Override
    public Result register(@RequestBody UserForm form) {
        log.info("注册用户,{},{}",form);
        User user = new User();
        BeanUtils.copyProperties(form,user);
        user.setBalance(0.0);
        user.setGrowth(0);
        user.setCredit(0);
        user.setLevel(0);
        User user1 = service.checkOnlyTel(user.getTel());
        if(user1 == null){
            service.registerUser(user);
        }else {
            return Result.fail("该手机号已经被注册");
        }
        return Result.success("注册成功");
    }

    /**
     * 账号登陆
     * @param username
     * @param password
     * @return
     */
    @Override
    public Result loginByPassword(String username, String password) {
        log.info("登录,{},{}",username,password);
        User user = service.loginByUsername(username, password);
        if(user!=null){
            HashMap<String, Object> payLoad = new HashMap<>();
            payLoad.put("userid",user.getUserId());
            log.info("pay{}",payLoad);
            String jwt = jwtHelper.createJWT(DateUtils.addDays(new Date(),1),payLoad);
            return Result.success(jwt);
        }else {
            return Result.fail("用户名或密码错误");
        }
    }

    /**
     * 短信登录
     * @param telPhoneNumber 手机号
     * @param check 验证码
     * @return
     */
    @Override
    public Result loginByCheck(String telPhoneNumber, String check) {
        log.info("短信登录手机号,验证码,{},{}",telPhoneNumber,check);
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String o = (String)valueOperations.get(telPhoneNumber);
        log.info("验证码,{}",o);
        if(o.equals(check)){
            User user = service.checkOnlyTel(telPhoneNumber);
            HashMap<String, Object> payLoad = new HashMap<>();
            payLoad.put("userId",user.getUserId());
            log.info("pay{}",payLoad);
            String jwt = jwtHelper.createJWT(DateUtils.addDays(new Date(),1),payLoad);
            return Result.success(jwt);
        }else {
            return Result.fail("验证码错误");
        }
    }
    /**
     * 发送短信
     * @param tel 手机号
     * @return
     */
    @Override
    public Result sendMessage(String tel) {
        String newcode="";
        AliyunSmsUtils.setNewcode();
        String code = AliyunSmsUtils.getNewcode();
        SendSmsResponse response = null;
        try {
            response = AliyunSmsUtils.sendSms(tel, code);
            ValueOperations valueOperations = redisTemplate.opsForValue();
            valueOperations.set(tel,code);
            return Result.success(response);
        } catch (ClientException e) {
            e.printStackTrace();
        }
      return Result.fail("发送失败");
    }

    /**
     * 修改个人资料
     * @param form
     * @return
     */
    @Override
    public Result updUser(UserForm form) {
        log.info("修改用户,{}",form);
        String tel = form.getTel();
        User user = service.checkOnlyTel(tel);
        user.getUserId();
        BeanUtils.copyProperties(form,user);
        int i = service.updUser(user);
        if(i == 1){
            return Result.success("修改成功");
        }else {
            return Result.fail("修改失败");
        }
    }

    /**
     * 增加用户积分
     * @param credit
     * @param userId
     * @return
     */
    @Override
    public Result increaseCredit(Integer credit,Integer userId) {
        log.info("增加积分,{},{}",credit,userId);
        int i = service.increaseCredit(credit,userId);
        if(i == 1){
            return Result.success("新增成功");
        }else {
            return Result.fail("新增失败");
        }
    }

    /**
     * 减少用户积分
     * @param credit
     * @param userId
     * @return
     */
    @Override
    public Result cutBackCredit(Integer credit,Integer userId) {
        log.info("减少积分,{},{}",credit,userId);
        int i = service.cutBackCredit(credit, userId);
        if(i == 1){
            return Result.success("减少成功");
        }else {
            return Result.fail("减少失败");
        }
    }


    /**
     * 新增成长值判断并成长值是否升级
     * @param growth
     * @param userId
     * @return
     */
    @Transactional
    @Override
    public Result increaseGrowthValue(int growth,int userId) {
        log.info("增加成长值,{},{}",growth,userId);
        int i = service.increaseGrowthValue(growth, userId);
        if(i == 1){
            User user = service.selUser(userId);
            int userGrowth = user.getGrowth();
            log.info("查询成长值,{}",userGrowth);
            int level = gradeService.selectLevel(userGrowth);
            int changeLevel = service.changeLevel(level, userId);
            log.info("等级为,{}",changeLevel);
            return Result.success("增加成功");
        }else {
            return Result.success("增加失败");
        }
    }


    /**
     * 查询账户余额
     * @param userId
     * @return
     */
    @Override
    public Result accountBalance(int userId) {
        User user = service.selUser(userId);
        Double balance = user.getBalance();
        return Result.success(balance);
    }


    /**
     * 充值钱包
     * @param form
     * @return
     */
    @Transactional
    @Override
    public Result recharge(UserFinanceForm form) {
        log.info("充值金额,{}",form);
        Double amount = form.getFundsAmount();
        String fundsAmount = amount.toString(amount);
        PayOrder order = new PayOrder();
        order.setOut_trade_no(form.getOutTradeNo());
        order.setDescription("充值");
        order.setSubject("充值钱包");

        order.setTotal_amount(form.getFundsAmount().toString());
        String s = "";
        try {
            s = aliPayService.aliPay(order);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        UserFinance finance = new UserFinance();

        Timestamp recordTime = null;
        try {
            recordTime =new Timestamp(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(form.getRecordTime()).getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        User user = service.selUser(form.getUserId());
        Double balance = user.getBalance();
        BeanUtils.copyProperties(form,finance);
        finance.setRecordTime(recordTime);

        log.info("finance,{}",finance);
        int i = iUserFinanceService.addUserFinance(finance);
        service.addMoney(balance+finance.getFundsAmount(),finance.getUserId());
        return Result.success(s);
    }

    /**
     * 上传图片
     * @param poster
     * @return
     */
    @Override
    public Result upload(MultipartFile poster) {
        String originalFilename = poster.getOriginalFilename();
        long millis = System.currentTimeMillis();

        String filename= millis+originalFilename;
        try {
            oss.putObject("hotel-rate",filename,poster.getInputStream());
            return Result.success(AppConstants.ossDomain+filename);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    @Override
    public Result findUser(int userId) {
        User user = service.selUser(userId);
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user,userVo);
        return Result.success(userVo);
    }
}

